
const bodyparser = require('koa-bodyparser');
const session = require('koa-session');
const onerror = require('koa-onerror');
const logger = require('koa-logger');
const cors = require('koa2-cors');
const json = require('koa-json')
const Koa = require('koa');
const app = new Koa();
const api = require('./routers/api')

onerror(app)
const CONFIG = {
    key: 'koa:sess',
    maxAge: 86400000,
    overwrite: true, /** (boolean) can overwrite or not (default true) */
    httpOnly: true, /** (boolean) httpOnly or not (default true) */
    signed: true, /** (boolean) signed or not (default true) */
    rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. default is false **/
    renew:false,
    siged:true
};

app.use(session(CONFIG, app));

app.use(bodyparser({
    enableTypes:['json', 'form', 'text']
}));

app.use(json());

app.use(logger());

app.use(require('koa-static')(__dirname + '/public'));

app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});
app.use(cors({ //解决跨域
    origin: function (ctx) {
        return '*';// 允许来自所有域名请求
    },
    maxAge: 5,
    credentials: true,  // 是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],  // 设置所允许的HTTP请求方法
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],  // 设置服务器支持的所有头信息字段
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] // 设置获取其他自定义字段
}));
// routes
app.use(api.routes(), api.allowedMethods()); 

// 监听端口、启动程序
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app;
